package com.shipwe.loans.ui.fragment

import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.shipwe.loans.R
import com.shipwe.loans.databinding.FragmentHomeBinding
import com.shipwe.loans.pro.ShipweFragment
import com.shipwe.loans.ui.activity.ActivityApply
import com.shipwe.loans.ui.activity.ActivityAuthSteps
import com.shipwe.loans.ui.activity.ActivityMain
import com.shipwe.loans.ui.activity.ActivityOrderDetails
import com.shipwe.loans.ui.adapter.ProductAdapter
import com.shipwe.loans.ui.presenter.HomePresenter
import com.shipwe.loans.ui.view.IHomeView
import com.shipwe.loans.utils.event.AppEventData
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.TestDataLibInvoke
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/18 16:52
 * @Annotation：首页
 */
class FragmentHome: ShipweFragment(), IHomeView {
    lateinit var binding: FragmentHomeBinding
    private var presenter: HomePresenter? = null
    //产品列表
    private var pAdapter: ProductAdapter? = null

    override fun getShipweRootView(inflater: LayoutInflater): View {
        binding = FragmentHomeBinding.inflate(inflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundResource(R.drawable.page_login_bg)
        setShipweTitleBarVisibility(View.VISIBLE)
        setShipweBackBtnRes(R.drawable.menu_black)
        setShipweRightBtnRes(R.drawable.customer_black)
        setShipweTextTitleVisibility(View.GONE)
        initHomeRefreshView()
        initHomeProductListView()
    }

    override fun initShipweListener() {
        //菜单
        rootViewBinding.rootBack.setOnClickListener {
            (getAct() as ActivityMain).showMainMenuFragment("Home Page")
        }
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Home Page")
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,"Home Page")
        }
        binding.homeProduct.setOnClickListener {
            presenter?.checkHomeProductType(1)
        }
        binding.homeNormalProduct.setOnClickListener {
            binding.homeProduct.callOnClick()
        }
        binding.homeApplied.setOnClickListener {
            presenter?.checkHomeProductType(2)
        }
        binding.homeNormalApplied.setOnClickListener {
            binding.homeApplied.callOnClick()
        }
    }

    override fun initShipweData() {
        presenter = HomePresenter(this)
        presenter?.loadHomeAllPermissionsAction()
        presenter?.checkHomeProductType(1)
    }

    /* 初始化刷新 */
    private fun initHomeRefreshView() {
        //禁止加载
        binding.homeRefreshView.setEnableLoadMore(false)
        binding.homeRefreshView.setEnableAutoLoadMore(false)
        binding.homeRefreshView.setOnRefreshListener {
            //刷新产品列表
            getAct().publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_PRODUCT_REFRESH))
        }
        binding.homeRefreshView.setOnLoadMoreListener {
            binding.homeRefreshView.finishLoadMore()
        }
    }

    /**
     * 产品列表
     */
    private fun initHomeProductListView(){
//        binding.homeProductListView.setHasFixedSize(true)
//        binding.homeProductListView.isNestedScrollingEnabled = false
//        binding.homeProductListView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        binding.homeProductListView.layoutManager = layoutManager
        pAdapter = ProductAdapter(binding.homeProductListView)
        pAdapter?.setOnItemChildClickListener { _, childView, position ->
            val item = this.pAdapter!!.getItem(position)
           presenter?.setHomeSelectProduct(item)
            when(childView.id){
                R.id.productApply -> {//申贷
                    if (item.optString("activeFlag") != "YES"){
                        return@setOnItemChildClickListener
                    }
                    presenter?.checkHomeAllPermissionsAgree()
                }
                R.id.productEmptyText -> {//去申请、取还款
                    if (item.optString("itemType") == "TYPE_APPLIED_EMPTY"){//去申请
                        binding.homeProduct.callOnClick()
                    } else {//去还款
                        publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_SHOW_REPAY))
                    }
                }
                R.id.productReviewing,
                R.id.productDisbursing,
                R.id.productRejected -> {//审核中、放款中、已拒绝
                    val pLogo = item.optString("logo")
                    val pName = item.optString("product")
                    val pToken = item.optString("token")
                    val pTitle = item.optString("name")
                    ActivityOrderDetails.start(requireContext(), pName, pToken)
                }
            }
        }
        binding.homeProductListView.adapter = pAdapter
    }

    override fun showHomeProductView(){
        binding.homeProduct.visibility = View.VISIBLE
        binding.homeNormalProduct.visibility = View.INVISIBLE

        binding.homeApplied.visibility = View.INVISIBLE
        binding.homeNormalApplied.visibility = View.VISIBLE
    }

    override fun showHomeAppliedView(){
        binding.homeProduct.visibility = View.INVISIBLE
        binding.homeNormalProduct.visibility = View.VISIBLE

        binding.homeApplied.visibility = View.VISIBLE
        binding.homeNormalApplied.visibility = View.INVISIBLE
    }

    /**
     * 设置产品列表
     */
    override fun showHomeProductList(pList: ArrayList<JSONObject>) {
        pAdapter?.data = pList
    }

    /**
     * 所有权限校验成功
     */
    override fun showHomeCheckPermissionSuccess() {
        //上报
        TestDataLibInvoke.sycData()
       presenter?.checkHomeAllStepsAction()
    }

    /**
     * 认证已完成 - 进入申贷页面
     */
    override fun showHomeLoanApplyPage(pName: String, pToken: String) {
        ActivityApply.start(requireContext(),pName,pToken)
    }

    /**
     * 认证未完成 - 进入认证页面
     */
    override fun showHomeProcessStepsPage() {
        dismissShipweLoading()
        onIntent(ActivityAuthSteps::class.java)
    }

    override fun onShipwePublishEvent(event: AppEventData) {
        super.onShipwePublishEvent(event)
        when(event.eventType){
            AppEventData.TYPE.SHIPWE_PRODUCT_REFRESHED -> {//刷新产品列表完成
                presenter?.loadHomeProductListAction()
            }
            AppEventData.TYPE.SHIPWE_PRODUCT_FINISHED -> {
                dismissShipweLoading()
            }
            else -> {

            }
        }
    }

    override fun dismissShipweLoading() {
        super.dismissShipweLoading()
        binding.homeRefreshView.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_PRODUCT_LIST_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_PRODUCT_LIST_END)
    }
}